package hibernate;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import controller.Index;
import pojo.User;
import dao.UserDAO;

@Repository("UserDAO")
public class HibernateUserDAO  implements UserDAO {
	private static final Logger logger = Logger.getLogger(HibernateUserDAO.class);
	private SessionFactory sessionFactory;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	@Transactional
	public User getUserInfo(String email) {
		Session session= sessionFactory.getCurrentSession();
        User user = null;
        String hql =String.format("from User s where s.email ='%s'",email);
        Query query = session.createQuery(hql);
       
        List<User> listUser = query.list();
        if(listUser.size() == 1)
            user = listUser.get(0);
        return user;
	}
	@Transactional
	public boolean checkSignin(String email, String password) {
		Session session= sessionFactory.getCurrentSession();
		try
        {
			
            String sql = "from User Where email =? and password = ?";
            Query query = session.createQuery(sql);
            query.setString(0, email);
            query.setString(1, password);
            User user = (User) query.uniqueResult();
            session.flush();
            if(user !=null) {
                return true;
            } 
        }
        catch(HibernateException e)
        {
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
		return false;
	}

	@Transactional
	public boolean addUser(User user) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.save(user);
            logger.info("Save new User  to database completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Svae new User to database got Error, this is it :",e);
            System.err.print(e); 
        }
        return false;
	}
	
	@Transactional
	public boolean checkRegisterEmail(String email) {
		Session session= sessionFactory.getCurrentSession();
		try
        {
			
            String sql = "from User Where email =?";
            Query query = session.createQuery(sql);
            query.setString(0, email);
            User user = (User) query.uniqueResult();
            session.flush();
            logger.info("Check email complete");
            if(user !=null) {
                return true;
            } 
        }
        catch(HibernateException e)
        {
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            logger.error("Error, this is it :",e);
            e.printStackTrace();
        }
		return false;
	}
	@Transactional
	public String[] listspecifications(String specification)
	{
		String[] frac = specification.split("@");
		return frac;
		
	}
	@Transactional
	public boolean updateUserDetail(String email,String firstname, String lastname,
			String zipcode, String phonenumber) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	String hql = "update User set firstname = '" + firstname +"', lastname ='" +lastname +"', zipcode ='"+zipcode+"', phonenumber ='"+phonenumber+"' where email='"+email +"'";
            Query query = session.createQuery(hql);
            query.executeUpdate();
            logger.info("Update user details completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Update user details got Error, this is it :",e);
            System.err.print(e); 
        }
        return false;
	}
	@Transactional
	public boolean updateUserPassword(String email, String passwordnew) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
        	String hql = "update User set password = '" + passwordnew +"' where email='"+email +"'";
            Query query = session.createQuery(hql);
            query.executeUpdate();
            logger.info("Update password user completed");
            return true;
        }
        catch(HibernateException e)
        {
        	logger.error("Update password got Error, this is it :",e);
            System.err.print(e); 
        }
        return false;
	}
	
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
	    User users = getUserInfo(username);
	    if (users == null) {
	        throw new UsernameNotFoundException("No user with username " +  username);
	    }
	    return (UserDetails) users;
	}

}
